<template>
  <div class="home-layout">
    <aside class="sidebar">
      <h1>风行旅途</h1>
      <hr class="sidebar-divider" />
      <nav>
        <ul>
          <li>
            <a
              href="#"
              :class="{ active: activeTab === 'train' }"
              @click.prevent="setActive('train')"
              >火车购票</a
            >
          </li>
          <li>
            <a href="#" :class="{ active: activeTab === 'meal' }" @click.prevent="setActive('meal')"
              >火车餐</a
            >
          </li>
          <li>
            <a
              href="#"
              :class="{ active: activeTab === 'hotel' }"
              @click.prevent="setActive('hotel')"
              >酒店</a
            >
          </li>
        </ul>
      </nav>
    </aside>
    <header class="header">
      <div style="margin-right: auto">{{ displayName }},欢迎您！</div>
      <div class="header-nav">
        <a href="#" @click.prevent="goToHistoryOrder">历史订单</a>
        <a href="#" @click.prevent="goToMessages">消息中心</a>
        <a href="https://gitee.com/wangzi-ma/software-engineering-homework" target="_blank"
          >关于我们</a
        >
      </div>
      <div class="avatar-wrapper">
        <img class="avatar" src="/logo.png" alt="头像" />
        <ul class="dropdown-menu">
          <li><a href="#" @click.prevent="goToPersonalCenter">个人中心</a></li>
          <li><a href="#" @click.prevent="goToWallet">我的钱包</a></li>
          <li><a href="#" @click.prevent="logout">退出登录</a></li>
        </ul>
      </div>
    </header>
    <main class="main-content">
      <div class="train-meal-container">
        <div v-if="!validOrders.length" class="no-ticket-message">
          <div class="alert warning">
            <h3>您当前没有有效的火车票订单</h3>
            <p>请先购买火车票后再进行餐食预定</p>
          </div>
        </div>

        <div v-else-if="!selectedOrder" class="order-list">
          <h2>请选择要订餐的火车票订单</h2>
          <div class="order-grid">
            <div
              v-for="order in validOrders"
              :key="order.orderId"
              class="order-card"
              @click="selectOrder(order)"
            >
              <div class="top">
                <span>{{ order.trainNumber }} ｜ {{ order.trainData }}</span>
                <span class="status">{{ getStatusText(order.ticketStatus) }}</span>
              </div>
              <div class="middle">
                <div class="stations">
                  <strong>{{ order.departureStationName }}</strong>
                  <span>→</span>
                  <strong>{{ order.arriveStationName }}</strong>
                </div>
                <div class="time">
                  {{ formatTime(order.departureTime) }} - {{ formatTime(order.arrivalTime) }}
                </div>
              </div>
              <div class="seat-info">
                <span
                  >车厢 {{ order.carriageNumber }} · 座位 {{ order.seatNumber }}（{{
                    order.seatType
                  }}）</span
                >
              </div>
              <div class="passenger">
                <span>乘客：{{ order.passengerName }} ｜ {{ order.passengerIdCard }}</span>
              </div>
              <div class="bottom">
                <div>
                  <span class="time">支付时间：{{ formatDateTime(order.paymentTime) }}</span>
                </div>
                <div class="price">￥{{ order.price.toFixed(2) }}</div>
              </div>
            </div>
          </div>
        </div>

        <div v-else>
          <div class="meal-header">
            <button class="back-btn" @click="selectedOrder = null">返回订单列表</button>
            <h2>火车餐预定 - {{ selectedOrder.trainNumber }}</h2>
          </div>
          <div class="meal-list">
            <div class="meal-grid">
              <div v-for="meal in meals" :key="meal.mealId" class="meal-card">
                <div class="meal-info">
                  <h3>{{ meal.mealName }}</h3>
                  <p class="meal-type">{{ meal.mealType }}</p>
                  <p class="description">{{ meal.description }}</p>
                  <p class="price">¥{{ meal.price }}</p>
                  <div class="quantity-control">
                    <button
                      class="quantity-btn"
                      @click="decreaseMealQuantity(meal)"
                      :disabled="!getMealQuantity(meal)"
                    >
                      -
                    </button>
                    <span class="quantity">{{ getMealQuantity(meal) }}</span>
                    <button
                      class="quantity-btn"
                      @click="increaseMealQuantity(meal)"
                      :disabled="!meal.available || getMealQuantity(meal) >= 3"
                    >
                      +
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="cart-summary" v-if="hasSelectedMeals">
            <h3>已选餐品</h3>
            <div class="selected-meals">
              <div
                v-for="[meal, quantity] in selectedMeals"
                :key="meal.mealId"
                class="selected-meal"
              >
                <span>{{ meal.mealName }} x {{ quantity }}</span>
                <span>¥{{ (meal.price * quantity).toFixed(2) }}</span>
              </div>
            </div>
            <div class="total">
              <span>总计：</span>
              <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <button class="checkout-btn" @click="showConfirmDialog">去结算</button>
          </div>
        </div>

        <div v-if="confirmDialogVisible" class="modal">
          <div class="modal-content">
            <h3>确认订单</h3>
            <div class="order-details">
              <div class="order-item" v-for="[meal, quantity] in selectedMeals" :key="meal.mealId">
                <div class="meal-info">
                  <span class="meal-name">{{ meal.mealName }}</span>
                  <span class="meal-quantity">x {{ quantity }}</span>
                </div>
                <div class="meal-price">
                  <span>单价：¥{{ meal.price }}</span>
                  <span>小计：¥{{ (meal.price * quantity).toFixed(2) }}</span>
                </div>
              </div>
              <div class="order-total">
                <span>订单总额：</span>
                <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
              </div>
              <div class="balance-info">
                <span>当前余额：</span>
                <span
                  :class="[
                    'balance',
                    userBalance !== null && userBalance < totalPrice ? 'insufficient' : '',
                  ]"
                >
                  ¥{{ userBalance?.toFixed(2) || '加载中...' }}
                </span>
                <span v-if="userBalance !== null && userBalance < totalPrice" class="warning-text">
                  (余额不足)
                </span>
              </div>
            </div>
            <div class="modal-footer">
              <button class="cancel-btn" @click="confirmDialogVisible = false">取消</button>
              <button
                class="confirm-btn"
                @click="submitOrder"
                :disabled="userBalance === null || userBalance < totalPrice"
              >
                确认购买
              </button>
            </div>
          </div>
        </div>

        <MealPaymentModal
          :visible="showPaymentModal"
          :userName="displayName"
          :orderItems="
            Array.from(selectedMeals.entries()).map(([meal, quantity]) => ({
              name: meal.mealName,
              price: meal.price,
              quantity: quantity,
              mealId: meal.mealId,
              mealType: meal.mealType,
            }))
          "
          :totalPrice="totalPrice"
          :trainTicketOrderId="selectedOrder?.orderId"
          @close="showPaymentModal = false"
          @success="handlePaymentSuccess"
          @fail="handlePaymentFail"
        />
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import type { TrainMeal } from '@/types/trainMeal'
import type { TrainOrderDTO } from '@/types/trainOrder'
import api from '@/utils/api'
import axios from 'axios'
import MealPaymentModal from '@/components/MealPaymentModal.vue'

const router = useRouter()
const activeTab = ref('meal')
const displayName = ref('')
const meals = ref<TrainMeal[]>([])
const validOrders = ref<TrainOrderDTO[]>([])
const selectedOrder = ref<TrainOrderDTO | null>(null)
const selectedMeals = ref<Map<TrainMeal, number>>(new Map())
const confirmDialogVisible = ref(false)
const showPaymentModal = ref(false)
const userBalance = ref<number | null>(null)

const hasSelectedMeals = computed(() => {
  return selectedMeals.value.size > 0
})

const totalPrice = computed(() => {
  let total = 0
  selectedMeals.value.forEach((quantity, meal) => {
    total += meal.price * quantity
  })
  return total
})

const getMealQuantity = (meal: TrainMeal) => {
  return selectedMeals.value.get(meal) || 0
}

const increaseMealQuantity = (meal: TrainMeal) => {
  const currentQuantity = getMealQuantity(meal)
  if (currentQuantity < 3) {
    selectedMeals.value.set(meal, currentQuantity + 1)
  } else {
    alert('每种餐品最多只能购买3份')
  }
}

const decreaseMealQuantity = (meal: TrainMeal) => {
  const currentQuantity = getMealQuantity(meal)
  if (currentQuantity > 0) {
    if (currentQuantity === 1) {
      selectedMeals.value.delete(meal)
    } else {
      selectedMeals.value.set(meal, currentQuantity - 1)
    }
  }
}

onMounted(() => {
  displayName.value = localStorage.getItem('username') || ''
  fetchValidTicket()
})

function goToHistoryOrder() {
  router.push({
    path: '/history',
    query: { username: displayName.value },
  })
}
function goToMessages() {
  router.push({
    path: '/messages',
    query: { username: displayName.value },
  })
}

function goToWallet() {
  // 跳转到钱包页面并传递昵称参数
  router.push({
    path: '/wallet', // 钱包页面路由路径
    query: { username: displayName.value }, // 传递参数
  })
}
function goToPersonalCenter() {
  router.push({
    path: '/center',
    query: { username: displayName.value },
  })
}
function logout() {
  /*退出登录 */
  // 可添加清除登录状态的逻辑，例如 localStorage 清理 token
  localStorage.removeItem('username')
  router.push('/login')
}
function setActive(tab: string) {
  activeTab.value = tab
  if (tab === 'hotel') {
    router.push('/hotel') // 跳转到酒店页面
  } else if (tab === 'train') {
    router.push('/home') // 回到主界面，也就是火车购票界面
  } else if (tab === 'meal') {
    router.push('/meal') // 当前页可写死或省略
  }
  /*else if (tab === 'history') {
    router.push('/history') // 将来你可以加这个页面
  }*/
}

// 格式化时间
function formatTime(time: string) {
  return time.slice(0, 5)
}

// 格式化日期时间
function formatDateTime(dt: string) {
  return dt?.replace('T', ' ').slice(0, 16) || '—'
}

// 获取状态文本
function getStatusText(status: number) {
  switch (status) {
    case 0:
      return '已支付'
    case 1:
      return '已退票'
    case 2:
      return '已使用'
    default:
      return '未知状态'
  }
}

// 获取有效的火车票订单
const fetchValidTicket = async () => {
  try {
    const response = await api.get(`/api/orders/user/${displayName.value}/summary`)
    console.log('获取到的所有订单数据:', response.data)

    // 获取最新的有效订单（已支付且未使用的订单）
    validOrders.value = response.data.filter((order: TrainOrderDTO) => {
      // 检查订单状态是否为已支付
      if (order.ticketStatus !== 0) return false

      // 结合车次日期和到达时间计算真正的到达时间
      const trainDate = new Date(order.trainData)
      const [arrivalHours, arrivalMinutes] = order.arrivalTime.split(':').map(Number)
      const arrivalDateTime = new Date(trainDate)
      arrivalDateTime.setHours(arrivalHours, arrivalMinutes, 0, 0)

      // 获取当前时间
      const now = new Date()

      // 计算距离到达时间是否还有1小时以上
      const timeDiff = arrivalDateTime.getTime() - now.getTime()
      const oneHourInMs = 60 * 60 * 1000

      return timeDiff > oneHourInMs
    })
    console.log('过滤后的有效订单:', validOrders.value)
  } catch (error) {
    console.error('获取火车票订单失败:', error)
  }
}

// 选择订单并获取餐食列表
const selectOrder = async (order: TrainOrderDTO) => {
  selectedOrder.value = order
  await fetchMeals()
}

// 获取可用的餐食列表
const fetchMeals = async () => {
  try {
    if (!selectedOrder.value) {
      console.error('没有选择订单')
      return
    }

    // 添加日志
    console.log('开始获取餐食列表，订单信息:', selectedOrder.value)

    // 先获取车次ID
    const trainIdResponse = await api.get(`/api/trains/number/${selectedOrder.value.trainNumber}`)

    if (!trainIdResponse.data) {
      console.error('未找到对应的车次ID')
      return
    }

    const trainId = trainIdResponse.data.trainId
    console.log('获取到车次ID:', trainId)

    // 使用车次ID获取餐食列表
    const response = await api.get('/api/meals', {
      params: {
        trainId: trainId,
      },
    })

    // 添加日志
    console.log('获取餐食列表成功:', response.data)

    meals.value = response.data
  } catch (error) {
    console.error('获取餐食列表失败:', error)
    if (axios.isAxiosError(error)) {
      console.error('错误详情:', error.response?.data)
      console.error('错误状态码:', error.response?.status)
    }
  }
}

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const res = await fetch(
      `http://localhost:9000/api/users?username=${encodeURIComponent(displayName.value)}`,
    )
    if (!res.ok) throw new Error('获取失败')
    const data = await res.json()
    // 从用户对象中提取余额字段
    userBalance.value = data.balance || 0
  } catch (e) {
    console.error('余额获取失败', e)
    userBalance.value = 0
  }
}

// 显示确认订单弹窗时获取余额
const showConfirmDialog = async () => {
  await fetchUserBalance()
  confirmDialogVisible.value = true
}

const submitOrder = async () => {
  if (!selectedOrder.value) return

  // 关闭确认对话框
  confirmDialogVisible.value = false

  // 显示支付弹窗
  showPaymentModal.value = true
}

// 处理支付成功
const handlePaymentSuccess = async () => {
  try {
    alert('支付成功，餐食订单已生成！')
    // 清空购物车
    selectedMeals.value.clear()
    // 刷新订单列表
    await fetchValidTicket()
    // 清空选中的订单，返回订单列表
    selectedOrder.value = null
  } catch (error) {
    console.error('处理支付成功失败:', error)
  }
}

// 处理支付失败
const handlePaymentFail = ({ status }: { status: string }) => {
  if (status === 'insufficient_balance') {
    alert('余额不足，请先充值')
  } else {
    alert('支付失败，请稍后重试')
  }
}
</script>

<style scoped>
/* 添加重置样式 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
/* 容器布局 */
.home-layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  transition: grid-template-columns 0.3s ease;
  grid-template-rows: 60px 1fr;
  grid-template-areas:
    'sidebar header'
    'sidebar main';
  height: 100vh;
  width: 100vw; /* 保证横向占满 */
}
.home-layout.collapsed {
  grid-template-columns: 60px 1fr;
}
/* 左侧边栏 */
.sidebar {
  grid-area: sidebar;
  background-color: #0086f6;
  color: white;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  transition: width 0.3s ease;
  overflow: hidden;
  position: relative;
}
/* 分隔线样式 */
.sidebar-divider {
  border: none;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  /*margin: 10px 0 20px;*/
  margin: 8px 0 16px;
}
/* 调整导航项间距和分隔 */
.sidebar li + li {
  border-top: 1px solid rgba(255, 255, 255, 0.15); /* 每项之间加线 */
  padding-top: 10px;
  margin-top: 8px;
}
/* 标题 */
.sidebar h1 {
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
}
/* 导航样式 */
.sidebar ul {
  list-style: none;
  padding: 0;
  width: 100%;
}
.sidebar li {
  margin: 8px 0;
}
.sidebar a {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  padding: 10px;
  border-radius: 6px;
  text-decoration: none;
  transition: background-color 0.2s ease;
}
.sidebar a:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.sidebar a.active {
  background-color: rgba(255, 255, 255, 0.25);
  font-weight: bold;
}

/* 右上角头部 */
.header {
  grid-area: header;
  display: flex;
  justify-content: space-between; /* 左右分开 */
  align-items: center;
  padding: 0 20px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
}
.header-nav {
  display: flex;
  margin-right: 20px;
}
.header-nav a {
  margin-right: 20px;
  color: #333;
  text-decoration: none;
}
.header-nav a:hover {
  text-decoration: underline;
}

/* 头像 */
.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  padding-top: 10px; /* 保证 hover 区域连贯 */
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover; /* 防止图片变形，裁剪填充 */
  transition: box-shadow 0.3s;
}
.avatar:hover {
  box-shadow: 0 0 8px rgba(0, 134, 246, 0.5);
}
/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  list-style: none;
  padding: 10px 0;
  margin: 0;
  min-width: 140px;
  display: none;
  z-index: 100;
}
.dropdown-menu li {
  padding: 10px 20px;
}
.dropdown-menu li a {
  text-decoration: none;
  color: #333;
  display: block;
  transition: background 0.2s;
}
.dropdown-menu li:hover {
  background-color: #f0f0f0;
}
/* 显示菜单：鼠标悬停时 */
.avatar-wrapper:hover .dropdown-menu {
  display: block;
}

/* 中间内容 */
.train-meal-container {
  padding: 20px;
}

.no-ticket-message {
  margin: 20px 0;
}

.alert {
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.alert.warning {
  background-color: #fff3cd;
  border: 1px solid #ffeeba;
  color: #856404;
}

.meal-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.meal-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: white;
}

.meal-info {
  padding: 10px;
}

.meal-type {
  color: #666;
  font-size: 14px;
  margin: 5px 0;
}

.description {
  color: #666;
  margin: 10px 0;
  font-size: 14px;
}

.price {
  color: #e74c3c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
}

.quantity-btn {
  padding: 5px 10px;
  border: 1px solid #ddd;
  background-color: #f8f9fa;
  cursor: pointer;
  border-radius: 4px;
}

.quantity-btn:disabled {
  background-color: #e9ecef;
  cursor: not-allowed;
}

.quantity {
  min-width: 30px;
  text-align: center;
}

.cart-summary {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.selected-meals {
  margin: 15px 0;
}

.selected-meal {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  padding: 5px 0;
  border-bottom: 1px solid #ddd;
}

.total {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
  font-size: 18px;
  font-weight: bold;
}

.checkout-btn {
  width: 100%;
  padding: 10px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.checkout-btn:hover {
  background-color: #218838;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.order-details {
  margin: 20px 0;
}

.order-item {
  margin: 15px 0;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.meal-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.meal-price {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
}

.order-total {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 2px solid #eee;
  display: flex;
  justify-content: space-between;
  font-size: 18px;
  font-weight: bold;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #e9ecef;
  color: #495057;
}

.confirm-btn {
  background-color: #28a745;
  color: white;
}

.cancel-btn:hover {
  background-color: #dee2e6;
}

.confirm-btn:hover {
  background-color: #218838;
}

.order-list {
  padding: 20px;
}

.order-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.order-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  transition: transform 0.2s;
  cursor: pointer;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.order-card .top {
  display: flex;
  justify-content: space-between;
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 16px;
}

.order-card .middle {
  margin: 15px 0;
}

.order-card .stations {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  margin-bottom: 5px;
}

.order-card .time {
  color: #666;
  font-size: 14px;
}

.order-card .seat-info,
.order-card .passenger {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
}

.order-card .bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.order-card .price {
  font-size: 18px;
  color: #e53935;
  font-weight: bold;
}

.status {
  color: #409eff;
  font-weight: 500;
}

.meal-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.balance-info {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
}

.balance {
  font-weight: bold;
  color: #28a745;
}

.balance.insufficient {
  color: #dc3545;
}

.warning-text {
  color: #dc3545;
  font-size: 14px;
}

.confirm-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
